package com.example.flowabledemo.service.impl;

import com.example.flowabledemo.common.HttpCode;
import com.example.flowabledemo.common.flowable.ProcessValues;
import com.example.flowabledemo.data.dto.ResponseResult;
import com.example.flowabledemo.data.entity.AaApproval;
import com.example.flowabledemo.data.mapper.AaProcessMapper;
import com.example.flowabledemo.data.pojo.SecUser;
import com.example.flowabledemo.service.AdminService;
import com.example.flowabledemo.service.FlowableService;
import com.example.flowabledemo.service.UserService;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminServiceImpl implements AdminService {

  @Autowired
  private FlowableService flowableService;
  @Autowired
  private UserService userService;

  @Transactional
  @Override
  public ResponseResult approvalLeave(String processId, Integer approval, String message) {
    AaApproval aaApproval = new AaApproval();
    SecUser user = userService.getUser();
    Task task = flowableService.getNewestTask(processId);
    String status = ProcessValues.PROCESS_STATUS_OK;
    Map<String, Object> map = new HashMap<>();
    map.put("approval", 1);
    if (approval == 1) {//同意
      map.put("approval", 1);
      aaApproval.setStatus(ProcessValues.APPROVAL_STATUS_YES);
    } else {//不同意
      map.put("approval", 0);
      //流程打回
      status = ProcessValues.PROCESS_STATUS_BACK;
      aaApproval.setStatus(ProcessValues.APPROVAL_STATUS_NO);
    }
    //添加注释
    flowableService.addCommand(task.getId(), processId, message);
    //提交任务
    flowableService.complete(task.getId(), map);

    aaApproval.setTaskId(task.getId());
    aaApproval.setCreateTime(new Date());
    aaApproval.setDepartmentCode(user.getDepartmentCode());
    aaApproval.setUsername(user.getUsername());
    aaApproval.setRemarks(message);
    aaApproval.setProcessId(processId);
    //记录一次操作
    flowableService.addApproval(aaApproval);
    //更新流程状态
    flowableService.updateProcessStatus(processId, status);
    return new ResponseResult(HttpCode.OK, "审批提交成功！");
  }
}
